<?php
declare (strict_types=1);

namespace app\admin\logic\finance;

use app\admin\logic\system\Log;
use app\admin\model\finance\Encashment as EncashmentModel;
use app\common\event\subscribes\notify\Notify as NotifyEvent;
use app\common\exception\LogicException;
use app\common\logic\Payment;
use app\user\logic\user\Account;
use app\user\logic\user\Balance;
use app\user\logic\user\Income;
use app\user\logic\user\IncomeFlow;
use think\facade\Event;

/**
 * 提现管理逻辑
 */
class Encashment extends EncashmentModel
{
    /**
     * 获取列表
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-06-23
     */
    public function getList($type)
    {
        // 验证数据
        if (in_array($type, ['index', 'done', 'wait', 'reject'])) {
            return $this->with(['user_name'])->scope($type)->order('create_time', 'DESC')->paginate($this->getListRows());
        } else {
            throw new LogicException('请求错误');
        }
    }

    /**
     * editEncashment
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/9/25
     *
     * @param Encashment $data
     * @param array      $param
     */
    public function editEncashment(Encashment $data, array $param)
    {
        $this->startTrans();
        try {
            // 取得验证器
            $status = $param['status'];
            // 参数
            $data->status = $status;
            // 如果失败了,需要添加失败原因
            if ($status == 3) {
                $data->reason = $param['reason'];
            }
            $re = $data->save();
            if (!$re) {
                throw new LogicException('处理失败');
            }

            if ($status == 2) {
                // 处理提现审核通过
                $key = 'encashment_success';
                $this->handleTransfer($data);
                // 操作日志
                Log::write('通过提现审核【' . $data->order_no . '】', 'encashment', 'action', true);
            } else if ($status == 3) {
                // 处理驳回，(驳回理由，发送消息)
                $key = 'encashment_fail';
                $this->handleRefund($data);
                // 操作日志
                Log::write('驳回提现审核【' . $data->order_no . '】', 'encashment', 'action', true);
            }

            // 通知
            $param = [
                'user' => $data->user_id,
                'type' => 'system_notify',
                'key'  => $key,
                'var'  => [
                    'user_name' => app(Account::class)->getUserNickName($data->user_id),
                    'money'     => $data->money,
                    'reason'    => $param['reason'] ?? ''
                ],
            ];

            Event::subscribe(NotifyEvent::class);
            Event::trigger('Notify', $param);
            $this->commit();

        } catch (LogicException $e) {
            $this->rollback();
            // throw $e;
            throw new LogicException('处理失败', $e->getMessage());
        }

    }

    /**
     * 提现处理成功
     *
     * @param $data
     */
    private function handleTransfer($data)
    {
        $type = $data->getAttr('type');
        // 处理提现
        if (0 == $type) {
            // 余额及流水变更，后台审核后操作
            app(Balance::class)->increaseUserBalance($data->user_id, $data->money, 11, 'user_encashment', $data->order_no, '收入提现到余额：' . $data->money);
        } else if (1 == $type) {
            // 微信
            app(Payment::class)->wxtrans($data);
        } else if (2 == $type) {
            // 支付宝
            app(Payment::class)->alitrans($data);
        }
    }

    /**
     * 提现处理失败
     *
     * @param $data
     */
    private function handleRefund($data)
    {
        // 将提现扣除的收入退回
        $this->increaseIncome($data->money, $data->user_id);
    }

    /**
     * 返还收入
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/9/25
     *
     * @param     $money
     * @param int $user_id
     */
    private function increaseIncome($money, int $user_id)
    {
        $user_income = Income::where('user_id', $user_id)->findOrEmpty();
        // 变更余额
        $user_income->income += $money;
        if (!$user_income->save()) {
            throw new LogicException('操作失败');
        }
        // 流水记录
        app(IncomeFlow::class)->updateFlow($user_id, 9, $money, $user_income->income, 0, 0, '提现失败退回收入');
    }
}
